<template>
  <div v-if="isVisible" class="test-injector" @click.self="hideInjector">
    <div class="test-panel">
      <div class="test-header">
        <h3>🧪 测试数据注入器</h3>
        <el-button 
          type="danger" 
          size="small" 
          @click="hideInjector"
          class="close-btn"
        >
          <el-icon><close /></el-icon>
          关闭
        </el-button>
      </div>
      
      <div class="test-content">
        <div class="test-section">
          <h4>📊 桩桶状态数据</h4>
          <p class="test-description">
            包含通过(蓝色)、漏桩(红色)、踢桩(橙色)等不同状态
          </p>
          <el-button 
            type="primary" 
            @click="injectConeStatus"
            :loading="injecting"
          >
            <el-icon><data-analysis /></el-icon>
            注入桩桶状态
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>📈 偏移数据</h4>
          <el-button 
            type="success" 
            @click="injectOffsetData"
            :loading="injecting"
          >
            <el-icon><trend-charts /></el-icon>
            注入偏移数据
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>⏱️ 时间数据</h4>
          <el-button 
            type="warning" 
            @click="injectTimeData"
            :loading="injecting"
          >
            <el-icon><timer /></el-icon>
            注入时间数据
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>⚠️ 罚时数据</h4>
          <el-button 
            type="danger" 
            @click="injectPenaltyData"
            :loading="injecting"
          >
            <el-icon><warning /></el-icon>
            注入罚时数据
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>🎯 全部数据</h4>
          <el-button 
            type="info" 
            @click="injectAllData"
            :loading="injecting"
          >
            <el-icon><magic-stick /></el-icon>
            注入全部测试数据
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>📋 成绩记录</h4>
          <p class="test-description">
            注入5条测试成绩记录，包含有效和无效成绩
          </p>
          <el-button 
            type="info" 
            @click="injectRecordsData"
            :loading="injecting"
          >
            <el-icon><document /></el-icon>
            注入成绩记录
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>🎥 视频数据</h4>
          <p class="test-description">
            注入测试视频文件到视频播放器
          </p>
          <el-button 
            type="primary" 
            @click="injectVideoData"
            :loading="injecting"
          >
            <el-icon><video-play /></el-icon>
            注入测试视频
          </el-button>
          <el-button 
            type="warning" 
            @click="forceInjectVideoData"
            :loading="injecting"
            style="margin-top: 8px;"
          >
            <el-icon><refresh /></el-icon>
            强制重新注入
          </el-button>
        </div>
        
        <div class="test-section">
          <h4>🔄 重置数据</h4>
          <el-button 
            type="default" 
            @click="resetAllData"
            :loading="injecting"
          >
            <el-icon><refresh /></el-icon>
            重置所有数据
          </el-button>
        </div>
      </div>
      
      <div class="test-info">
        <p><strong>使用说明：</strong></p>
        <ul>
          <li>点击各个按钮可以注入不同类型的测试数据</li>
          <li>数据会直接更新到UI组件中</li>
          <li>可以随时重置数据或关闭此面板</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { ElMessage } from 'element-plus'

// 注入父组件的数据和方法
const offsetData = inject('offsetData', ref({}))
const currentTime = inject('currentTime', ref(0))
const penaltyCount = inject('penaltyCount', ref(0))
const groundTouch = inject('groundTouch', ref(false))
const conesVisualizer = inject('conesVisualizer', ref(null))
const records = inject('records', ref([]))
const videos = inject('videos', ref([]))

// 组件状态
const isVisible = ref(false)
const injecting = ref(false)

// 测试数据
const testData = {
  // 桩桶状态数据 (1=通过, 0=漏桩, 2=踢桩, -1=未检测)
  coneStatus: {
    "001": "1", "002": "1", "003": "2", "004": "1", "005": "1", 
    "006": "1", "007": "1", "008": "1", "009": "1", "010": "1", 
    "011": "1", "012": "2", "013": "1", "014": "1", "015": "1", 
    "016": "1", "017": "0", "018": "1", "019": "1", "020": "1"
  },
  
  // 偏移数据
  offsetData: {
    "001dir": "l", "001val": "100", "002dir": "r", "002val": "50", 
    "003dir": "r", "003val": "50", "004dir": "r", "004val": "70", 
    "005dir": "l", "005val": "50", "006dir": "r", "006val": "50", 
    "007dir": "l", "007val": "60", "008dir": "r", "008val": "195", 
    "009dir": "l", "009val": "50", "010dir": "r", "010val": "80", 
    "011dir": "l", "011val": "50", "012dir": "r", "012val": "60", 
    "013dir": "l", "013val": "50", "014dir": "r", "014val": "50", 
    "015dir": "l", "015val": "70", "016dir": "r", "016val": "50", 
    "017dir": "l", "017val": "90", "018dir": "r", "018val": "80", 
    "019dir": "l", "019val": "50", "020dir": "r", "020val": "50"
  },
  
  // 时间数据
  timeData: 12.345,
  
  // 罚时数据
  penaltyData: 2,
  
  // 浮脚数据
  groundTouchData: false,
  
  // 成绩记录数据
  recordsData: [
    {
      id: Date.now() - 300000,
      timestamp: '2024-01-15 14:30:25',
      time: 12.345,
      penaltyCount: 2,
      penaltyTime: 0.4,
      finalScore: 12.745,
      valid: true,
      groundTouch: false,
      completed: true
    },
    {
      id: Date.now() - 600000,
      timestamp: '2024-01-15 14:25:18',
      time: 11.892,
      penaltyCount: 1,
      penaltyTime: 0.2,
      finalScore: 12.092,
      valid: true,
      groundTouch: false,
      completed: true
    },
    {
      id: Date.now() - 900000,
      timestamp: '2024-01-15 14:20:45',
      time: 13.156,
      penaltyCount: 3,
      penaltyTime: 0.6,
      finalScore: 13.756,
      valid: false,
      groundTouch: true,
      completed: true
    },
    {
      id: Date.now() - 1200000,
      timestamp: '2024-01-15 14:15:32',
      time: 10.234,
      penaltyCount: 0,
      penaltyTime: 0.0,
      finalScore: 10.234,
      valid: true,
      groundTouch: false,
      completed: true
    },
    {
      id: Date.now() - 1500000,
      timestamp: '2024-01-15 14:10:15',
      time: 14.567,
      penaltyCount: 4,
      penaltyTime: 0.8,
      finalScore: 15.367,
      valid: false,
      groundTouch: true,
      completed: true
    }
  ]
}

// 显示注入器
function showInjector() {
  isVisible.value = true
  console.log('🧪 测试数据注入器已显示')
}

// 隐藏注入器
function hideInjector() {
  isVisible.value = false
  console.log('🧪 测试数据注入器已隐藏')
}

// 注入桩桶状态数据
async function injectConeStatus() {
  injecting.value = true
  try {
    console.log('📊 注入桩桶状态数据:', testData.coneStatus)
    
    // 如果有ConeVisualizer组件引用，直接更新桩桶状态
    if (conesVisualizer.value && conesVisualizer.value.handleConesResultMessage) {
      console.log('🔍 调用ConeVisualizer.handleConesResultMessage方法')
      console.log('📊 传递的数据:', testData.coneStatus)
      // 直接传递数据对象给ConeVisualizer的方法
      conesVisualizer.value.handleConesResultMessage(testData.coneStatus)
      console.log('✅ 桩桶状态已通过ConeVisualizer组件更新')
    } else {
      console.warn('⚠️ ConeVisualizer组件引用不可用，无法更新桩桶状态')
      console.log('🔍 conesVisualizer.value:', conesVisualizer.value)
      if (conesVisualizer.value) {
        console.log('🔍 可用方法:', Object.keys(conesVisualizer.value))
      }
    }
    
    ElMessage.success('桩桶状态数据已注入！请查看桩桶可视化区域')
  } catch (error) {
    console.error('❌ 注入桩桶状态数据失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入偏移数据
async function injectOffsetData() {
  injecting.value = true
  try {
    console.log('📈 注入偏移数据:', testData.offsetData)
    offsetData.value = { ...offsetData.value, ...testData.offsetData }
    console.log('✅ 偏移数据已更新:', offsetData.value)
    ElMessage.success('偏移数据已注入！请查看偏移曲线分析区域')
  } catch (error) {
    console.error('❌ 注入偏移数据失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入时间数据
async function injectTimeData() {
  injecting.value = true
  try {
    console.log('⏱️ 注入时间数据:', testData.timeData)
    currentTime.value = testData.timeData
    console.log('✅ 时间数据已更新:', currentTime.value)
    ElMessage.success(`时间数据已注入！当前时间: ${testData.timeData}秒`)
  } catch (error) {
    console.error('❌ 注入时间数据失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入罚时数据
async function injectPenaltyData() {
  injecting.value = true
  try {
    console.log('⚠️ 注入罚时数据:', testData.penaltyData)
    penaltyCount.value = testData.penaltyData
    groundTouch.value = testData.groundTouchData
    console.log('✅ 罚时数据已更新:', penaltyCount.value)
    ElMessage.success(`罚时数据已注入！罚时次数: ${testData.penaltyData}次`)
  } catch (error) {
    console.error('❌ 注入罚时数据失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入全部数据
async function injectAllData() {
  injecting.value = true
  try {
    console.log('🎯 开始注入全部测试数据...')
    
    // 依次注入各种数据
    await new Promise(resolve => setTimeout(resolve, 200))
    console.log('📊 注入桩桶状态数据')
    if (conesVisualizer.value && conesVisualizer.value.handleConesResultMessage) {
      console.log('🔍 调用ConeVisualizer.handleConesResultMessage方法')
      console.log('📊 传递的数据:', testData.coneStatus)
      conesVisualizer.value.handleConesResultMessage(testData.coneStatus)
      console.log('✅ 桩桶状态已通过ConeVisualizer组件更新')
    } else {
      console.warn('⚠️ ConeVisualizer组件引用不可用，无法更新桩桶状态')
    }
    
    await new Promise(resolve => setTimeout(resolve, 200))
    console.log('📈 注入偏移数据')
    offsetData.value = { ...offsetData.value, ...testData.offsetData }
    
    await new Promise(resolve => setTimeout(resolve, 200))
    console.log('⏱️ 注入时间数据')
    currentTime.value = testData.timeData
    
    await new Promise(resolve => setTimeout(resolve, 200))
    console.log('⚠️ 注入罚时数据')
    penaltyCount.value = testData.penaltyData
    groundTouch.value = testData.groundTouchData
    
    await new Promise(resolve => setTimeout(resolve, 200))
    console.log('📋 注入成绩记录数据')
    records.value = []
    records.value.push(...testData.recordsData)
    
    console.log('✅ 全部测试数据注入完成!')
    ElMessage.success('全部测试数据已注入！请查看各个UI区域的效果')
  } catch (error) {
    console.error('❌ 注入全部数据失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入成绩记录数据
async function injectRecordsData() {
  injecting.value = true
  try {
    console.log('📋 注入成绩记录数据:', testData.recordsData)
    
    // 清空现有记录
    records.value = []
    
    // 添加测试记录
    records.value.push(...testData.recordsData)
    
    console.log('✅ 成绩记录已注入:', records.value.length, '条记录')
    ElMessage.success(`已注入${records.value.length}条成绩记录！请查看成绩记录表格`)
  } catch (error) {
    console.error('❌ 注入成绩记录失败:', error)
    ElMessage.error('注入失败')
  } finally {
    injecting.value = false
  }
}

// 注入视频数据
async function injectVideoData() {
  injecting.value = true
  try {
    console.log('🎥 注入测试视频数据...')
    
    // 创建测试视频数据，格式与VideoPlayback组件兼容
    const testVideo = {
      id: Date.now(), // 使用时间戳作为唯一ID
      name: '速度过桩训练视频',
      duration: '0:45', // 45秒
      size: '12.5 MB',
      timestamp: new Date().toLocaleString(),
      url: new URL('/src/assets/b0df25c361fc53701d2454784795d6d0.mp4', import.meta.url).href // 使用Vite正确的静态资源路径
    }
    
    console.log('📹 测试视频数据:', testVideo)
    console.log('🔗 视频URL:', testVideo.url)
    
    // 将视频添加到视频列表的开头
    if (videos.value) {
      // 检查是否已经存在相同的视频（避免重复添加）
      const existingVideo = videos.value.find(v => v.name === testVideo.name)
      if (!existingVideo) {
        videos.value.unshift(testVideo) // 添加到列表开头
        console.log('✅ 视频已添加到视频列表，当前视频数量:', videos.value.length)
        console.log('📋 当前视频列表:', videos.value)
        ElMessage.success(`测试视频已注入！视频名称: ${testVideo.name}`)
      } else {
        console.log('⚠️ 视频已存在，跳过添加')
        console.log('🔍 现有视频列表:', videos.value)
        console.log('🔍 找到的重复视频:', existingVideo)
        ElMessage.warning('该测试视频已存在，无需重复添加')
      }
    } else {
      console.warn('⚠️ 视频列表不可用，无法注入视频')
      ElMessage.error('视频列表不可用，无法注入视频')
    }
    
  } catch (error) {
    console.error('❌ 注入视频数据失败:', error)
    ElMessage.error('视频注入失败')
  } finally {
    injecting.value = false
  }
}

// 强制重新注入视频数据（即使已存在也重新添加）
async function forceInjectVideoData() {
  injecting.value = true
  try {
    console.log('🎥 强制重新注入测试视频数据...')
    
    // 创建测试视频数据，格式与VideoPlayback组件兼容
    const testVideo = {
      id: Date.now(), // 使用时间戳作为唯一ID
      name: '速度过桩训练视频',
      duration: '0:45', // 45秒
      size: '12.5 MB',
      timestamp: new Date().toLocaleString(),
      url: new URL('/src/assets/b0df25c361fc53701d2454784795d6d0.mp4', import.meta.url).href // 使用Vite正确的静态资源路径
    }
    
    console.log('📹 强制注入视频数据:', testVideo)
    console.log('🔗 视频URL:', testVideo.url)
    
    // 将视频添加到视频列表的开头（强制添加，不检查重复）
    if (videos.value) {
      // 先移除可能存在的同名视频
      const existingIndex = videos.value.findIndex(v => v.name === testVideo.name)
      if (existingIndex !== -1) {
        videos.value.splice(existingIndex, 1)
        console.log('🗑️ 移除已存在的同名视频')
      }
      
      // 添加新视频到列表开头
      videos.value.unshift(testVideo)
      console.log('✅ 视频已强制添加到视频列表，当前视频数量:', videos.value.length)
      console.log('📋 当前视频列表:', videos.value)
      ElMessage.success(`测试视频已强制重新注入！视频名称: ${testVideo.name}`)
    } else {
      console.warn('⚠️ 视频列表不可用，无法注入视频')
      ElMessage.error('视频列表不可用，无法注入视频')
    }
    
  } catch (error) {
    console.error('❌ 强制注入视频数据失败:', error)
    ElMessage.error('视频强制注入失败')
  } finally {
    injecting.value = false
  }
}

// 重置所有数据
async function resetAllData() {
  injecting.value = true
  try {
    console.log('🔄 重置所有测试数据...')
    
    offsetData.value = {}
    currentTime.value = 0
    penaltyCount.value = 0
    groundTouch.value = false
    records.value = []
    
    console.log('✅ 所有数据已重置')
    ElMessage.success('所有数据已重置！')
  } catch (error) {
    console.error('❌ 重置数据失败:', error)
    ElMessage.error('重置失败')
  } finally {
    injecting.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  showInjector,
  hideInjector,
  isVisible
})
</script>

<style scoped>
.test-injector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.test-panel {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  max-width: 600px;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 16px 16px 0 0;
}

.test-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  border-radius: 8px;
}

.test-content {
  padding: 24px;
}

.test-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  border-left: 4px solid #409EFF;
}

.test-section h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.test-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
}

.test-section .el-button {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
}

.test-info {
  padding: 16px 24px;
  background: #f0f7ff;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 16px 16px;
}

.test-info p {
  margin: 0 0 8px 0;
  color: #303133;
  font-weight: 600;
}

.test-info ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  font-size: 13px;
  line-height: 1.6;
}

.test-info li {
  margin-bottom: 4px;
}

/* 暗色主题样式 */
[data-theme="dark"] .test-panel {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
}

[data-theme="dark"] .test-header {
  background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-primary) 100%);
  border-bottom-color: var(--border-color);
}

[data-theme="dark"] .test-header h3 {
  color: var(--text-primary);
}

[data-theme="dark"] .test-section {
  background: var(--bg-secondary);
  border-left-color: var(--neon-blue);
}

[data-theme="dark"] .test-section h4 {
  color: var(--text-primary);
}

[data-theme="dark"] .test-description {
  color: var(--text-secondary);
}

[data-theme="dark"] .test-info {
  background: var(--bg-secondary);
  border-top-color: var(--border-color);
}

[data-theme="dark"] .test-info p {
  color: var(--text-primary);
}

[data-theme="dark"] .test-info ul {
  color: var(--text-secondary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .test-injector {
    padding: 10px;
  }
  
  .test-panel {
    max-height: 90vh;
  }
  
  .test-header {
    padding: 16px 20px;
  }
  
  .test-content {
    padding: 20px;
  }
  
  .test-section {
    margin-bottom: 20px;
    padding: 12px;
  }
}
</style>
